package com.cmge.ad.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.cmge.ad.cache.ehcache.EhCacheCacheManager;
import com.cmge.ad.interfaces.req.AlbumListReq;
import com.cmge.ad.interfaces.req.ArticleListReq;
import com.cmge.ad.interfaces.req.CommentListReq;
import com.cmge.ad.interfaces.req.CommentReq;
import com.cmge.ad.interfaces.req.ConfigReq;
import com.cmge.ad.interfaces.req.FeedBackReq;
import com.cmge.ad.interfaces.req.PictureInfoReq;
import com.cmge.ad.interfaces.req.PictureListReq;
import com.cmge.ad.interfaces.req.RegisterReq;
import com.cmge.ad.interfaces.req.VersionUpdateReq;
import com.cmge.ad.interfaces.req.ZanCommentReq;
import com.cmge.ad.interfaces.req.ZanReq;
import com.cmge.ad.interfaces.resp.AlbumListResp;
import com.cmge.ad.interfaces.resp.ArticleListResp;
import com.cmge.ad.interfaces.resp.CommentListResp;
import com.cmge.ad.interfaces.resp.CommentResp;
import com.cmge.ad.interfaces.resp.ConfigResp;
import com.cmge.ad.interfaces.resp.FeedBackResp;
import com.cmge.ad.interfaces.resp.MenuListResp;
import com.cmge.ad.interfaces.resp.PictureInfoResp;
import com.cmge.ad.interfaces.resp.PictureListResp;
import com.cmge.ad.interfaces.resp.RegisterResp;
import com.cmge.ad.interfaces.resp.VersionUpdateResp;
import com.cmge.ad.interfaces.resp.ZanCommentResp;
import com.cmge.ad.interfaces.resp.ZanResp;
import com.cmge.ad.interfaces.vo.Album;
import com.cmge.ad.interfaces.vo.Article;
import com.cmge.ad.interfaces.vo.ChildMenu;
import com.cmge.ad.interfaces.vo.ParentMenu;
import com.cmge.ad.interfaces.vo.Picture;
import com.cmge.ad.interfaces.vo.Version;
import com.cmge.ad.mapper.MainMapper;
import com.cmge.ad.model.Comment;
import com.cmge.ad.model.User;
import com.cmge.ad.service.MainService;
import com.cmge.ad.util.Constant;
import com.cmge.ad.util.SuprUtil;

@Service
@Transactional(isolation=Isolation.DEFAULT,rollbackFor=Exception.class)
public class MainServiceImpl implements MainService{
	
	@Autowired
	private MainMapper mainMapper;
	
	@Autowired
	private EhCacheCacheManager cacheManager;
	
	@Override
	public ZanResp zan(ZanReq zanReq) {
		ZanResp resp = new ZanResp(Constant.DEAL_SUCCESS);
		int type = zanReq.getType();
		// 根据类型去指定表中找到数据更新zan
		if(type == 1){
			// 段子  根据id去段子表中更新赞
			mainMapper.zanArticle(zanReq.getId());
		}else if(type == 2){
			// 图片  根据id去图片表中更新赞
			mainMapper.zanPicture(zanReq.getId());
		}else if(type == 3){
			// 相册  根据id去相册表中更新赞
			mainMapper.zanAlbum(zanReq.getId());
		}else{
			resp.setResultCode(Constant.DEAL_FAIL);
		}
		
		return resp;
	}
	
	@Override
	public RegisterResp register(RegisterReq registerReq) {
		RegisterResp resp = new RegisterResp(Constant.DEAL_SUCCESS);
		
		try {
			registerReq.setDeviceName(URLDecoder.decode(registerReq.getDeviceName(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		mainMapper.register(registerReq);
		resp.setUserId(String.valueOf(registerReq.getId()));
		return resp;
	}
	
	@Override
	public CommentResp comment(CommentReq commentReq) {
		CommentResp resp = new CommentResp(Constant.DEAL_SUCCESS);
		try {
			commentReq.setComment(URLDecoder.decode(commentReq.getComment(), "utf-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		mainMapper.comment(commentReq);
		return resp;
	}
	
	@Override
	public ZanCommentResp zanComment(ZanCommentReq zanReq) {
		ZanCommentResp resp = new ZanCommentResp(Constant.DEAL_SUCCESS);
		mainMapper.zanComment(zanReq);
		return resp;
	}
	
	@Override
	public CommentListResp getCommentList(CommentListReq commentReq) {
		CommentListResp resp = new CommentListResp(Constant.DEAL_SUCCESS);
		List<Comment> commentList = mainMapper.getCommentList(commentReq);
		resp.setCommentList(commentList);
		return resp;
	}
	
	@Override
	public MenuListResp getMenuList() {
		// 从缓存读取数据
		MenuListResp resp = (MenuListResp) cacheManager.get(EhCacheCacheManager.DEFAULT_REGION, "menuList");
		if(null != resp){
			return resp;
		}
		
		resp = new MenuListResp(Constant.DEAL_SUCCESS);
		// 获取一级分类
		List<ParentMenu> menuList = mainMapper.getParentMenu();
		// 遍历查询每个一级分类的子分类
		if(menuList != null && menuList.size() > 0){
			for(ParentMenu menu : menuList){
				List<ChildMenu> childList = mainMapper.getChildMenuByPId(menu.getId());
				menu.setMenuList(childList);
			}
		}
		
		resp.setMenuList(menuList);
		// 放入缓存中
		cacheManager.put("DefaultRegion", "menuList", resp);
		
		return resp;
	}
	
	@Override
	public ArticleListResp getArticle(ArticleListReq req,HttpServletRequest request) {
		String basePath = getPathInfo(request);
		
		ArticleListResp resp = new ArticleListResp(Constant.DEAL_SUCCESS);
		List<Article> articleList = null;
		
		// 判断刷新方向
		int orientation = req.getOrientation();
		if(orientation == 1){
			// 如果向上刷新  则取大于lastId最新的
			articleList = mainMapper.getNewArticleList(req);
		}else if(orientation == 2){
			// 如果向下刷新  则取小于lastId老数据
			articleList = mainMapper.getOldArticleList(req);
		}
		
		// 图片路径拼装
		if (!SuprUtil.isEmptyCollection(articleList)) {
			// 查询图片前缀来源   fileServer来自文件服务器  其他则是来源本地文件 upload下
			ConfigReq configReq = new ConfigReq("PicSource");
			String picSource = getConfigValueInfo(configReq);
			for (Article article : articleList) {
				if (article.getType() == 2 && !StringUtils.isEmpty(article.getLocationUrl())) {
					if(!StringUtils.isEmpty(picSource) && picSource.equals("fileServer")){
						article.setLocationUrl("http://adfile.cmge.com/qule/" + article.getLocationUrl().replace("/upload/", ""));
					}else{
						article.setLocationUrl(basePath + article.getLocationUrl());
					}
				}
			}
		}

		resp.setArticleList(articleList);
		return resp;
	}
	
	@Override
	public AlbumListResp getAlbum(AlbumListReq req, HttpServletRequest request) {
		AlbumListResp resp = new AlbumListResp(Constant.DEAL_SUCCESS);
		List<Album> albumList = null;
		// 判断刷新方向
		int orientation = req.getOrientation();
		if(orientation == 1){
			// 如果向上刷新  则取大于lastId最新的
			albumList = mainMapper.getNewAlbum(req);
		}else if(orientation == 2){
			// 如果向下刷新  则取小于lastId老数据
			albumList = mainMapper.getOldAlbum(req);
		}
		
		if(!SuprUtil.isEmptyCollection(albumList)){
			// 遍历相册  获取每个相册的数据
			for(Album album : albumList){
				List<Picture> picList = getPicList(album.getId(),request);
				if (!SuprUtil.isEmptyCollection(picList)) {
					album.setSize(picList.size());
					// 查询图片前缀来源   fileServer来自文件服务器  其他则是来源本地文件 upload下
					ConfigReq configReq = new ConfigReq("PicSource");
					String picSource = getConfigValueInfo(configReq);
					Picture pic = picList.get(album.getIndex());
					if (null != pic && !StringUtils.isEmpty(pic.getLocationUrl())) {
						if(!StringUtils.isEmpty(picSource) && picSource.equals("fileServer")){ // 来自文件服务器
							album.setLocationUrl(pic.getLocationUrl().replace("/upload/", ""));
						}else{
							album.setLocationUrl(pic.getLocationUrl());
						}
						
						album.setWidth(pic.getWidth());
						album.setHeight(pic.getHeight());
					}
				}
			}
		}
		
		resp.setAlbumList(albumList);
		return resp;
	}
	
	@Override
	public PictureInfoResp getPictureInfo(PictureInfoReq req, HttpServletRequest request) {
		PictureInfoResp resp = new PictureInfoResp(Constant.DEAL_SUCCESS);
		// 先判断缓冲中有没有该相册数据
		List<Picture> picList = getPicList(req.getAlbumId(),request);
		resp.setPicList(picList);
		return resp;
	}
	
	@Override
	public PictureListResp getPicture(PictureListReq req,HttpServletRequest request) {
		PictureListResp resp = new PictureListResp(Constant.DEAL_SUCCESS);
		List<Album> albumList = null;
		// 判断刷新方向
		int orientation = req.getOrientation();
		if(orientation == 1){
			// 如果向上刷新  则取大于lastId最新的
			albumList = mainMapper.getNewAlbumList(req);
		}else if(orientation == 2){
			// 如果向下刷新  则取小于lastId老数据
			albumList = mainMapper.getOldAlbumList(req);
		}
		
		if(!SuprUtil.isEmptyCollection(albumList)){
			// 遍历相册  获取每个相册的数据
			for(Album album : albumList){
				List<Picture> picList = getPicList(album.getId(),request);
				album.setPictureList(picList);
			}
		}
		
		resp.setAlbumList(albumList);
		return resp;
	}
	
	@Override
	public FeedBackResp feedBack(FeedBackReq req) {
		FeedBackResp resp = new FeedBackResp(Constant.DEAL_SUCCESS);
		mainMapper.feedBack(req);
		return resp;
	}
	
	@Override
	public VersionUpdateResp versionUpdate(VersionUpdateReq req) {
		VersionUpdateResp resp = new VersionUpdateResp(Constant.DEAL_SUCCESS);
		Version version = mainMapper.versionUpdate(req);
		resp.setVersion(version);
		return resp;
	}
	
	/**
	 * 获取配置项值
	 * @param configReq
	 * @return
	 */
	public String getConfigValueInfo(ConfigReq configReq) {
		// 从缓存中获取配置项
		String result = (String) cacheManager.get(EhCacheCacheManager.DEFAULT_REGION, configReq.getConfigKey());
		if (StringUtils.isEmpty(result)) {
			result = mainMapper.getConfigValue(configReq);
			// 放入缓冲中
			cacheManager.put(EhCacheCacheManager.DEFAULT_REGION, configReq.getConfigKey(), result);
		}
		
		return result;
	}
	
	/**
	 * 获取上下文路径 用于图片地址拼装
	 * @param request
	 * @return
	 */
	public String getPathInfo(HttpServletRequest request) {
		// 从缓存中获取配置项
		String basePath = (String) cacheManager.get(EhCacheCacheManager.DEFAULT_REGION, "basePath");
		if (StringUtils.isEmpty(basePath)) {
			InetAddress addr = null;
			try {
				addr = InetAddress.getLocalHost();
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
			String ip=addr.getHostAddress().toString();
			basePath = request.getScheme() + "://"
					+ ip + ":" + request.getServerPort()
					+ request.getContextPath();
			// 放入缓冲中
			cacheManager.put(EhCacheCacheManager.DEFAULT_REGION, "basePath", basePath);
		}
		
		return basePath;
	}
	
	/**
	 * 从缓冲中获取某个相册的所有图片
	 * @param albumId
	 * @return
	 */
	public List<Picture> getPicList(int albumId,HttpServletRequest request) {
		String basePath = getPathInfo(request);
		// 从缓存中获取配置项
		List<Picture> picList = (List<Picture>) cacheManager.get(EhCacheCacheManager.DEFAULT_REGION, String.valueOf(albumId));
		if (SuprUtil.isEmptyCollection(picList)) {
			picList = mainMapper.getPictureListByAlbumId(albumId);
			// 放入缓冲中
			if(!SuprUtil.isEmptyCollection(picList)){
				// 查询图片前缀来源   fileServer来自文件服务器  其他则是来源本地文件 upload下
				ConfigReq configReq = new ConfigReq("PicSource");
				String picSource = getConfigValueInfo(configReq);
				for (Picture pic : picList) {
					if (!StringUtils.isEmpty(pic.getLocationUrl())) {
						if(!StringUtils.isEmpty(picSource) && picSource.equals("fileServer")){
							pic.setLocationUrl("http://adfile.cmge.com/qule/" + pic.getLocationUrl().replace("/upload/", ""));
						}else{
							pic.setLocationUrl(basePath + pic.getLocationUrl());
						}
					}
				}
				cacheManager.put(EhCacheCacheManager.DEFAULT_REGION, String.valueOf(albumId), picList);
			}
		}
		
		return picList;
	}
	
	@Override
	public ConfigResp getConfigValue(ConfigReq configReq) {
		ConfigResp resp = new ConfigResp(Constant.DEAL_SUCCESS);
		resp.setValue(getConfigValueInfo(configReq));
		return resp;
	}
	
	@Override
	public boolean exist(User user) {
		return mainMapper.exist(user) > 0 ? true : false;
	}
	
	@Override
	public void addUser(User user) {
		mainMapper.addUser(user);
	}
}
